//
//  HNMainViewController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2016/12/13.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "HNServiceViewController.h"


@interface HNServiceViewController ()<UIScrollViewDelegate>{
    BOOL isFromStart;
}

@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;

//contentScrollView的高度
@property (nonatomic,assign)CGFloat contentHeight;

//轮播图变量
@property(nonatomic, strong)UIScrollView  *scrollView;      //声明一个UIScrollView
@property(nonatomic, strong)UIPageControl *pageControl;     //声明一个UIPageControl
@property(nonatomic, strong)NSMutableArray  *arrayImages;          //存放图片的数组
@property(nonatomic, strong)NSMutableArray *viewController; //存放UIViewController的可变数组
@property (nonatomic,strong)NSTimer *timer;
@property (nonatomic,strong)UIView *rxView;



@property (nonatomic,strong)NSMutableArray *docterListSource;
@property (nonatomic,assign)NSInteger docterCount ;
@property (nonatomic,strong)UIView *shoppingView;//商品详情View
@property (nonatomic,assign)CGFloat *shoppingHeight;//商品详情高度


@property (nonatomic,assign) int cur;

@end

@implementation HNServiceViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //在其他离开改页面的方法同样加上下面代码
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

-(void)drawView{
    //    _contentScrollView.backgroundColor = RGBJ(248);
    
    //    self.contentScrollView =
    _contentScrollView.delegate = self;
    _contentScrollView.backgroundColor = RGBJ(233);
    _docterListSource = [[NSMutableArray alloc]init];
    _docterCount = 0;
    
    //    //设置轮播图
    [self setAdsVC:nil];
    //
    //
    //    //设置搜索
//    [self setSearchBtn];
    
    
}


-(void)initData{
    //获取轮播图数据
    self.arrayImages = [[NSMutableArray alloc]init];
    [self getAdsImage];
    
    self.cur = 1;//分页初始赋值
    
  
    
    
}


-(void)setAdsVC:(NSMutableArray *)imageArr{
    _contentHeight = 0;
    if (!imageArr) {
        //       self.arrayImages = [NSMutableArray arrayWithObjects:@"ads_1.png",@"54521417567978.png", nil];
    }else{
        self.arrayImages = imageArr;
    }
    
    self.adsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Width*3/5)];
    _contentHeight = _contentHeight + self.adsView.frame.size.height;
    _contentScrollView.contentSize = CGSizeMake(kScreen_Width,_contentHeight);
    [self.contentScrollView addSubview:self.adsView];
    CGFloat height = self.adsView.frame.size.height;
    CGFloat width = self.adsView.frame.size.width;
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width,height)];
    [_scrollView setPagingEnabled:YES];
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    [_scrollView setDelegate:self];
    [_scrollView setBackgroundColor:[UIColor lightGrayColor]];
    
    //ContentSize 这个属性对于UIScrollView挺关键的，取决于是否滚动。
    [_scrollView setContentSize:CGSizeMake(width * [self.arrayImages count], height)];
    [self.adsView addSubview:self.scrollView];
    
    [self.scrollView setBounces:YES];
    
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width/2-80, self.scrollView.frame.size.height - 20, 160, 20)];
    //    [_pageControl setBackgroundColor:[UIColor blackColor]];
    
    _pageControl.currentPage = 0;
    _pageControl.numberOfPages = [self.arrayImages count];
    [_pageControl addTarget:self action:@selector(chagePage:) forControlEvents:UIControlEventValueChanged];
    [self.adsView addSubview:self.pageControl];
    
    _viewController = [[NSMutableArray alloc] init];
    
    for (NSInteger i = 0; i < [self.arrayImages count]; i++) {
        [_viewController addObject:[NSNull null]];
    }
    
    //加载每张图
    for (NSInteger i = 0; i<self.arrayImages.count; i++) {
        [self loadScrollViewPage:i];
    }
    
    //    _timer = [NSTimer scheduledTimerWithTimeInterval:self.arrayImages.count*2 target:self selector:@selector(scrollPages) userInfo:nil repeats:YES];
    
    
}





#pragma mark - 轮播图展现
-(void)loadScrollViewPage:(NSInteger)page
{
    if (page >= self.arrayImages.count) {
        return;
    }
    
    UIImageView *adsImageView = [self.viewController objectAtIndex:page];
    if ((NSNull *)adsImageView == [NSNull null])
    {
        adsImageView = [[UIImageView alloc] init];
        [self.viewController replaceObjectAtIndex:page withObject:adsImageView];
    }
    
    if (adsImageView.superview == nil) {
        CGRect frame = self.scrollView.frame;
        frame.origin.x = CGRectGetWidth(frame) * page;
        frame.origin.y = 0;
        adsImageView.frame = frame;
        
        [self.scrollView addSubview:adsImageView];
        
        NSLog(@"%@",self.arrayImages);
        
        if (self.arrayImages) {
            NSString *imageStr = [NSString stringWithFormat:@"%@%@",url_Base,[[self.arrayImages objectAtIndex:page] objectForKey:@"advertImg"]];
            NSLog(@"%@",imageStr);
            
            [adsImageView sd_setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"轮播.png"]];
        }
        
        
    }
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWidth = CGRectGetWidth(self.scrollView.frame);
    NSInteger page = floor((self.scrollView.contentOffset.x -pageWidth/2)/pageWidth) ;
    if (self.scrollView.contentOffset.x<0) {
        _pageControl.currentPage = self.arrayImages.count - 1;
    }else if(self.scrollView.contentOffset.x > (self.arrayImages.count - 1)*kScreen_Width){
        _pageControl.currentPage = 0;
    }else{
        _pageControl.currentPage = page + 1;
    }
    [self loadScrollViewPage:page];
    //    [self loadScrollViewPage:page-1];
    //    [self loadScrollViewPage:page];
    //    [self loadScrollViewPage:page+1];
}

//- (IBAction)changePage:(id)sender
//{
//    NSInteger page = self.pageControl.currentPage;
//
//    [self loadScrollViewPage:page - 1];
//    [self loadScrollViewPage:page];
//    [self loadScrollViewPage:page + 1];

//    CGRect bounds = self.scrollView.bounds;
//    bounds.origin.x = Kwidth * page - 1;
//    bounds.origin.y = 0;
//    [self.scrollView scrollRectToVisible:bounds animated:YES];
//}


//NSTimer
-(void)scrollPages{
    //    ++self.pageControl.currentPage;
    CGFloat pageWidth = CGRectGetWidth(self.scrollView.frame);
    if (isFromStart) {
        [self.scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
        _pageControl.currentPage = 0;
    }
    else
    {
        _pageControl.currentPage ++;
        
        [self.scrollView setContentOffset:CGPointMake(pageWidth*_pageControl.currentPage, self.scrollView.bounds.origin.y)];
        
        [self loadScrollViewPage:_pageControl.currentPage];
    }
    if (_pageControl.currentPage == _pageControl.numberOfPages - 1) {
        isFromStart = YES;
    }
    else
    {
        isFromStart = NO;
    }
}

#pragma mark - 轮播图 UIPageControl
-(void)chagePage:(UIPageControl *)pageControl
{
    //    _pageControl.currentPage
}


#pragma mark - scrollViewDelegate
// contentScrollView 已经滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //    CGFloat offset = _noListNormalH - 58 - 36 - 36;
    //    CGFloat contentScrolloffectY = _contentScrollView.contentOffset.y;
    //    if (_noListNormalH != 0) {
    //        if (contentScrolloffectY >= offset) {
    //            self.srarchView.alpha = 1;
    //            [self.listHeadView setHidden:YES];
    //            [self.listOtherHeadView setHidden:NO];
    //            [self.searchBackground setBackgroundColor:RGB(244, 244, 244)];
    //        }else{
    //            self.srarchView.alpha = contentScrolloffectY/offset;
    //            [self.listHeadView setHidden:NO];
    //            [self.listOtherHeadView setHidden:YES];
    //            [self.searchBackground setBackgroundColor:RGB(255, 255, 255)];
    //        }
    //    }
    
    //    NSLog(@"scrollViewDidScroll");
}

// contentScrollView 开始拖动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //    NSLog(@"scrollViewWillBeginDragging");
}

// contentScrollView 结束拖动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    //    NSLog(@"scrollViewDidEndDragging");
}


#pragma mark - 初始化数据--轮播图

-(void)getAdsImage{
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_Advert_list parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取轮播图失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSMutableArray * obj = [NSMutableArray arrayWithArray:[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",obj);
            
            _timer = [NSTimer scheduledTimerWithTimeInterval:obj.count*2 target:self selector:@selector(scrollPages) userInfo:nil repeats:YES];
            
            [_adsView removeFromSuperview];
            
            
            
            //    //设置轮播图
            [self setAdsVC:obj];
            //
            //
            //    //设置搜索
//            [self setSearchBtn];
            
            
            
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取轮播图失败"];
    }];
    
    
}





@end
